<template>
  <div class="app-container">
    <el-card class="filter-container" shadow="never">
      <div>
        <i class="el-icon-search"></i>
        <span>筛选搜索</span>
        <el-button
          style="float: right"
          type="primary"
          @click="handleSearchList()"
          size="small"
        >
          查询搜索
        </el-button>
        <el-button
          style="float: right; margin-right: 15px"
          @click="handleResetSearch()"
          size="small"
        >
          重置
        </el-button>
      </div>
      <div style="margin-top: 15px">
        <el-form
          :inline="true"
          :model="listQuery"
          size="small"
          label-width="140px"
        >
          <el-form-item label="社区名称：">
            <el-input
              v-model="listQuery.communityName"
              class="input-width"
              placeholder="请输入名称"
            ></el-input>
          </el-form-item>
          <el-form-item label="省市区：" prop="province">
            <single-address ref="singleAddressSearch"></single-address>
          </el-form-item>
          <!--          <el-form-item label="街道名称：">-->
          <!--            <el-input-->
          <!--              v-model="listQuery.deptName"-->
          <!--              class="input-width"-->
          <!--              placeholder="请输入"-->
          <!--            ></el-input>-->
          <!--          </el-form-item>-->
        </el-form>
      </div>
    </el-card>
    <el-card class="operate-container" shadow="never">
      <i class="el-icon-tickets"></i>
      <span>数据列表</span>
      <el-button size="mini" class="btn-add" @click="handleAdd()"
        >新增社区</el-button
      >
      <!--      <el-button-->
      <!--        style="margin-right:20px"-->
      <!--        class="btn-add"-->
      <!--        type="info"-->
      <!--        size="mini"-->
      <!--      >导入</el-button>-->
    </el-card>
    <div class="table-container">
      <el-table
        ref="adminTable"
        :data="list"
        style="width: 100%"
        v-loading="listLoading"
        border
      >
        <el-table-column label="社区名称" align="center">
          <template slot-scope="scope">{{ scope.row.communityName }}</template>
        </el-table-column>
        <el-table-column label="省市区" align="center">
          <template slot-scope="scope">{{ scope.row | setAdrInfo }}</template>
        </el-table-column>
        <el-table-column label="街道名称" align="center">
          <template slot-scope="scope">{{ scope.row.street }}</template>
        </el-table-column>
        <el-table-column label="详细地址" align="center">
          <template slot-scope="scope">{{ scope.row.address }}</template>
        </el-table-column>
        <el-table-column label="合作开始时间" width="160" align="center">
          <template slot-scope="scope">{{
            scope.row.startTime | formatDateTime
          }}</template>
        </el-table-column>
        <el-table-column label="合作结束时间" width="180" align="center">
          <template slot-scope="scope">{{
            scope.row.endTime | formatDateTime
          }}</template>
        </el-table-column>
        <el-table-column label="状态" align="center">
          <template slot-scope="scope">{{
            scope.row.status == "0" ? "已停止" : "合作中"
          }}</template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              @click="handleUpdate(scope.$index, scope.row)"
              >编辑
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        layout="total, sizes,prev, pager, next,jumper"
        :current-page.sync="listQuery.pageNum"
        :page-size="listQuery.pageSize"
        :page-sizes="[10, 15, 20]"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="isEdit ? '编辑社区' : '新增社区'"
      :visible="dialogVisible"
      @close="closedialogVisible"
      width="40%"
    >
      <el-form
        :model="admin"
        :rules="rules"
        ref="courseFrom"
        label-width="150px"
        size="small"
      >
        <el-form-item label="社区名称：" prop="communityName">
          <el-col :span="15">
            <el-input
              v-model="admin.communityName"
              class="input-width"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="合作时间：" prop="dateRange">
          <el-date-picker
            v-model="admin.dateRange"
            type="daterange"
            align="right"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            @change="dateRangeChange"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="省市区：" required>
          <single-address
            v-if="dialogVisible"
            ref="singleAddress"
            class="input-width"
          ></single-address>
        </el-form-item>
        <el-form-item label="街道名称：" prop="street">
          <el-col :span="15">
            <el-input
              v-model="admin.street"
              class="input-width"
              size="small"
            ></el-input>
          </el-col>
        </el-form-item>
        <el-form-item label="详细地址：" prop="address">
          <el-col :span="15">
            <el-input
              v-model="admin.address"
              class="input-width"
              size="small"
            ></el-input>
          </el-col>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closedialogVisible" size="small">取 消</el-button>
        <el-button type="primary" @click="handleDialogConfirm()" size="small"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  umsCommunityList,
  umsCommunitySave,
  umsCommunityUpdate
} from '@/api/dept'
import { formatDate } from '@/utils/date'
import SingleAddress from '@/components/SingleAddress'
import moment from 'moment'

const defaultListQuery = {
  pageNum: 1,
  pageSize: 10
}
export default {
  name: 'AdminList',
  components: { SingleAddress },
  data () {
    return {
      adress: [],
      optionsAdress: [],
      props: {
        value: 'code',
        label: 'name',
        children: 'cities'
      },
      courseTypeOptions: '',
      addUms: false,
      typeOptions: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      pickerOptions: {},
      value: [],
      options: [],
      listQuery: Object.assign({}, defaultListQuery),
      list: null,
      total: null,
      listLoading: false,
      dialogVisible: false,
      admin: {
        address: '',
        cityCode: '',
        communityName: '',
        countyCode: '',
        province: '',
        dateRange: []
      },
      isEdit: false,
      status: [{ name: '非合作' }, { name: '合作中' }],
      count: 1,
      rules: {
        communityName: [
          {
            required: true,
            message: '请输入社区名称',
            trigger: 'blur'
          }
        ],
        dateRange: [
          {
            type: 'array',
            required: true,
            message: '请选择时间',
            trigger: 'blur'
          }
        ],
        street: [
          {
            required: true,
            message: '请输入街道名称',
            trigger: 'blur'
          }
        ],
        address: [
          {
            required: true,
            message: '请输入详细地址',
            trigger: 'blur'
          }
        ]
      }
    }
  },
  created () {
    // this.getProvice()
    this.getList()

    setTimeout(() => {
      this.$refs.singleAddressSearch.init()
    }, 10)
  },
  filters: {
    formatDateTime (time) {
      if (time == null || time === '') {
        return 'N/A'
      }
      const date = new Date(time)
      return formatDate(date, 'yyyy-MM-dd hh:mm:ss')
    },
    setAdrInfo (row) {
      const { province, cityCode, countyCode } = row
      if (province && province.indexOf('{') !== -1) {
        return `${JSON.parse(province).provName}-${JSON.parse(cityCode).cityName
          }-${JSON.parse(countyCode).countyName}`
      } else {
        return ''
      }
    }
  },
  methods: {
    handleAdd () {
      this.admin = {
        address: '',
        cityCode: '',
        communityName: '',
        countyCode: '',
        province: '',
        dateRange: []
      }

      setTimeout(() => {
        this.$refs.singleAddress.reset()
        this.$refs.singleAddress.init()
      }, 10)
      this.dialogVisible = true
      this.isEdit = false
      this.addUms = true
    },
    closedialogVisible () {
      this.dialogVisible = false
      this.addUms = false
    },
    handleDialogConfirm () {
      this.$refs['courseFrom'].validate((valid) => {
        if (valid) {
          this.listLoading = true

          const {
            provCode,
            provName,
            cityCode,
            cityName,
            countyCode,
            countyName
          } = this.$refs.singleAddress.getProdReleaseAreaList()[0]
          const addrInfo = {
            province: JSON.stringify({ provCode, provName }),
            cityCode: JSON.stringify({ cityCode, cityName }),
            countyCode: JSON.stringify({ countyCode, countyName })
          }

          const {
            communityName,
            address,
            street,
            startTime,
            endTime,
            id
          } = this.admin

          const params = {
            communityName,
            address,
            street,
            startTime,
            endTime,
            ...addrInfo
          }

          if (id > -1) {
            params.id = id
          }

          if (!this.addUms) {
            // 修改
            umsCommunityUpdate(params).then((response) => {
              this.dialogVisible = false
              this.listLoading = false
              this.$message({
                message: response.message,
                type: 'success'
              })
              this.addUms = false
              // this.$refs.tree.setCheckedKeys([])
              this.getList()
            })
          } else {
            // 新增
            umsCommunitySave(params).then((response) => {
              this.dialogVisible = false
              this.listLoading = false
              this.$message({
                message: response.message,
                type: 'success'
              })
              this.addUms = false
              // this.$refs.tree.setCheckedKeys([])
              this.getList()
            })
          }
        } else {
          this.$message({
            message: '验证失败',
            type: 'error',
            duration: 1000
          })
          return false
        }
      })
    },
    handleResetSearch () {
      this.$refs.singleAddressSearch.reset(true)

      this.listQuery = Object.assign({}, defaultListQuery)
    },
    handleSearchList () {
      this.listQuery.pageNum = 1
      this.listQuery = {
        ...this.listQuery,
        ...this.$refs.singleAddressSearch.getProdReleaseAreaList()[0],
        provinceCode: this.$refs.singleAddressSearch.getProdReleaseAreaList()[0]
          .provCode
      }
      this.getList()
    },
    handleSizeChange (val) {
      this.listQuery.pageNum = 1
      this.listQuery.pageSize = val
      this.getList()
    },
    handleCurrentChange (val) {
      this.listQuery.pageNum = val
      this.getList()
    },
    handleUpdate (index, row) {
      const { province, cityCode, countyCode } = row
      setTimeout(() => {
        this.$refs.singleAddress.init({
          ...JSON.parse(province),
          ...JSON.parse(cityCode),
          ...JSON.parse(countyCode)
        })
        this.$refs.singleAddress.setDefValue([
          JSON.parse(province).provCode,
          JSON.parse(cityCode).cityCode,
          JSON.parse(countyCode).countyCode
        ])
      }, 10)
      // this.admin = Object.assign({}, row)
      row.dateRange = row.startTime ? [row.startTime, row.endTime] : []

      this.admin = Object.assign({}, row)

      this.dialogVisible = true
      this.isEdit = true
      this.addUms = false
    },
    dateRangeChange (e) {
      this.admin.startTime = moment(e[0]).format()
      this.admin.endTime = moment(e[1]).format()
      // console.log(this.content);
    },
    getList () {
      this.listLoading = true
      umsCommunityList(this.listQuery).then((response) => {
        this.listLoading = false
        this.list = response.data.list
        this.total = response.data.total
      })
    }
  }
}
</script>
<style>
.el-date-editor .el-range-separator {
  padding: 0 5px;
  /*line-height: 32px;*/
  width: 15%;
  color: #303133;
}
.el-date-editor--daterange.el-input__inner {
  width: 100%;
}
</style>
